package cn.xo68.boot.web.web.exception;

import cn.xo68.boot.web.properties.WebCoreProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@ConditionalOnMissingBean( name = {"exceptionHandleController"})
@Controller("exceptionHandleController")
public class ExceptionHandleController {

    private static Logger logger= LoggerFactory.getLogger(ExceptionHandleController.class);

    @Autowired
    protected WebCoreProperties webCoreProperties;

    @GetMapping({"${wuxie.webcore.system-error-redirt-path:/error/sys}"})
    public String errorPage(HttpServletRequest request, Model model, Exception ex){
        //ModelAndView mv=new ModelAndView();
        Object statusObj= request.getAttribute("javax.servlet.error.status_code");

        String errorMessage = ex.getMessage();
        Exception tmpException= ex;
        int status = 200;
        if(statusObj!=null && statusObj instanceof Integer){
            status = (int) statusObj;
            switch (status){
                case 404:
                    errorMessage = "Not found";
                    tmpException= new IOException("文件未找到，可能是模板文件或静态文件不存在");
                    break;
            }
        }

        Object requestUrlObj=request.getAttribute("javax.servlet.error.request_uri");
        String requestUrl = "";
        if(requestUrlObj!=null && requestUrlObj instanceof String){
            requestUrl = (String) requestUrlObj;
            model.addAttribute("errorUrl", requestUrl);
            logger.error("["+requestUrl+"]发生异常",tmpException);
        }


        model.addAttribute("title",webCoreProperties.getErrorTitle());
        if(webCoreProperties.isShowSystemError()){
            model.addAttribute("error",errorMessage);
            model.addAttribute("exception", tmpException);
        }else {
            model.addAttribute("error",webCoreProperties.getErrorMessage());
            model.addAttribute("exception", null);
        }

        //mv.setViewName(webCoreProperties.getErrorViewName());
        return webCoreProperties.getErrorViewName();
    }
}
